package com.zzu.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzu.base.common.enums.ResultStatusEnum;
import com.zzu.base.common.pojo.LoginUser;
import com.zzu.base.entity.UserAvatarDO;
import com.zzu.base.exception.ProcessException;
import com.zzu.base.mapper.UserAvatarMapper;
import com.zzu.base.service.UserAvatarService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Service
public class UserAvatarServiceImpl extends ServiceImpl<UserAvatarMapper, UserAvatarDO>implements UserAvatarService {
    @Resource
    private UserAvatarMapper userAvatarMapper;
    @Value("${file.storage-root}")
    private String projectRoot;
    @Override
    public String addUserAvatar(MultipartFile file) {
        String fileSuffix = getFileSuffix(file);
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId=loginUser.getUser().getId();
        // 3. 构建文件名和存储路径
        String fileName = userId + fileSuffix; // 用用户ID命名，如 1001.png
        String avatarDirPath = projectRoot + File.separator + "user" + File.separator + "avatar";
        // 4. 创建存储目录（若不存在）
        File avatarDir = new File(avatarDirPath);
        if (!avatarDir.exists()) {
            if(avatarDir.mkdirs()){
                log.debug("{}目录创建",avatarDirPath);
            }else {
                throw new ProcessException(ResultStatusEnum.INTERNAL_SERVER_ERROR,"文件保存错误");
            }
        }

        File destFile = new File(avatarDirPath + File.separator+ fileName);
        try {
            file.transferTo(destFile);
        }catch (IOException e){
            throw new ProcessException(ResultStatusEnum.INTERNAL_SERVER_ERROR,"文件保存失败");
        }
        UserAvatarDO userAvatarDO = new UserAvatarDO();
        userAvatarDO.setUserId(userId);
        String url = "/user/avatar/" + fileName;
        userAvatarDO.setUrl(url);
        QueryWrapper<UserAvatarDO>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserAvatarDO oldUserAvatarDO = userAvatarMapper.selectOne(queryWrapper);
        if(oldUserAvatarDO == null){
            userAvatarMapper.insert(userAvatarDO);
        }else{
            String oldFileName = oldUserAvatarDO.getUrl().replace("/user/avatar/", "");
            File oldFile = new File(avatarDirPath + File.separator + oldFileName);            if (oldFile.exists() && !oldFile.delete()) {
                log.warn("旧头像文件删除失败，路径：{}", oldFile.getAbsolutePath());
                throw new ProcessException(ResultStatusEnum.INTERNAL_SERVER_ERROR,"头像更新失败");
            }
            userAvatarDO.setId(oldUserAvatarDO.getId());
            userAvatarMapper.updateById(userAvatarDO);
        }
        return  url;
    }

    private static String getFileSuffix(MultipartFile file) {
        if(file.isEmpty()){
            throw new  ProcessException( ResultStatusEnum.BAD_REQUEST,"文件为空");
        }
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
           throw new ProcessException(ResultStatusEnum.BAD_REQUEST,"仅支持图片格式（JPG、PNG等）");
        }
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            throw new ProcessException(ResultStatusEnum.BAD_REQUEST,"错误的文件名");
        }
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (fileSuffix.isEmpty()) {
            throw new ProcessException(ResultStatusEnum.BAD_REQUEST,"错误的文件后缀");
        }
        return fileSuffix;
    }

    @Override
    public String getUserAvatarUrl() {
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId=loginUser.getUser().getId();
        QueryWrapper<UserAvatarDO>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserAvatarDO userAvatarDO = userAvatarMapper.selectOne(queryWrapper);
        if(userAvatarDO == null){
            throw new ProcessException(ResultStatusEnum.BAD_REQUEST,"用户未上传头像");
        }
        return userAvatarDO.getUrl();
    }
}
